package com.wlts.wzy.LMGoodsModule.updateUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.linkedmall.model.v20180116.*;
import com.kuaishou.merchant.open.api.KsMerchantApiException;
import com.kuaishou.merchant.open.api.client.AccessTokenKsMerchantClient;
import com.kuaishou.merchant.open.api.request.KsMerchantItemStatusUpdateRequest;
import com.kuaishou.merchant.open.api.response.KsMerchantItemStatusUpdateResponse;
import com.wlts.wzy.Base.BaseEntity;
import com.wlts.wzy.KSUserModule.entity.KsOauth;
import com.wlts.wzy.KSUserModule.entity.KsStoreUser;
import com.wlts.wzy.KSUserModule.service.IKsOauthService;
import com.wlts.wzy.KSUserModule.service.IKsStoreUserService;
import com.wlts.wzy.LMGoodsModule.entity.LmGoods;
import com.wlts.wzy.LMGoodsModule.entity.LmGoodsDetails;
import com.wlts.wzy.LMGoodsModule.entity.LmSelfGoods;
import com.wlts.wzy.LMGoodsModule.service.ILmGoodsDetailsService;
import com.wlts.wzy.LMGoodsModule.service.ILmGoodsService;
import com.wlts.wzy.LMGoodsModule.service.ILmSelfGoodsService;
import com.wlts.wzy.configBean.KsConfig.KsConfigInfo;
import com.wlts.wzy.configBean.LmConfig.LmConfig;
import com.wlts.wzy.expand.MyLambdaQueryWrapper;
import com.wlts.wzy.util.CopyUtils;
import com.wlts.wzy.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Component
public class LmGoodsUpdate {
    @Autowired
    private ILmGoodsService lmGoodsService;
    @Autowired
    private ILmGoodsDetailsService lmGoodsDetailsService;
    @Autowired
    private ILmSelfGoodsService lmSelfGoodsService;
    @Autowired
    private IKsStoreUserService ksStoreUserService;
    @Autowired
    private IKsOauthService ksOauthService;


    private static final IAcsClient client = LmConfig.client;

    @Scheduled(fixedDelay = 120 * 1000)
//    @PostConstruct
    public void updateLmGoods() throws ClientException {

        int pageNumber = 1;
        int pageSize = 20;

        while (true) {

            Set<Long> down = new HashSet<>();

            QueryBizItemListRequest request = new QueryBizItemListRequest();
            request.setBizId(LmConfig.LZ_BIZ_ID);
            request.setPageNumber(pageNumber);
            request.setPageSize(pageSize);

            QueryBizItemListResponse resp = client.getAcsResponse(request);

      //       System.out.println(JSON.toJSONString(resp));

            List<QueryBizItemListResponse.Item> itemList = resp.getItemList();

            List<LmGoods> lmGoodsList = itemList.stream().map(item -> {

                MyLambdaQueryWrapper<LmGoods> queryWrapper = new MyLambdaQueryWrapper<>();

                queryWrapper.eq(LmGoods::getItemId, item.getItemId());
                queryWrapper.eq(BaseEntity::getDelFlag, "0");
                LmGoods lmGoods = lmGoodsService.getOne(queryWrapper);
                if (lmGoods == null) {
                    lmGoods = new LmGoods();
                } else {
                    if (lmGoods.getCanSell() && !item.getCanSell()) {
                        down.add(lmGoods.getItemId());
                    }
                }
                CopyUtils.copyProperties(item, lmGoods);
                lmGoods.setMainPicPrl(item.getMainPicUrl());
                lmGoods.setSkuList(JSON.toJSONString(item.getSkuList()));
                lmGoods.setExtJson(item.getExtJson());
                lmGoods.setLmItemId(item.getLmItemId());
                return lmGoods;
            }).collect(Collectors.toList());
            if (lmGoodsList.size() > 0) {
                lmGoodsService.saveOrUpdateBatch(lmGoodsList);
            }


            /**
             * 下架所有用户不可售商品
             */
//            try {
//                downSelfGoods(down);
//            }catch (Exception e){
//                e.printStackTrace();
//            }

            if (itemList.size() < pageSize) {
                break;
            }

            pageNumber += 1;
        }


    }

    private void downSelfGoods(Set<Long> down) {

        if (down.size() > 0) {

            Map<String, Set<LmSelfGoods>> downMap = new HashMap<>();

            MyLambdaQueryWrapper<LmSelfGoods> selfWrapper = new MyLambdaQueryWrapper<>();
            selfWrapper.eq(BaseEntity::getDelFlag, "0");
            selfWrapper.eq(LmSelfGoods::getKsSellStatus, 1);//快手上级状态 0未上架 1已经上架 2已经下架

            List<LmSelfGoods> selfGoodsList = lmSelfGoodsService.list(selfWrapper);

            selfGoodsList.forEach(lmSelfGoods -> {
                Set<LmSelfGoods> itemSet = downMap.get(lmSelfGoods.getUserUuid());
                if (itemSet == null) {
                    itemSet = new HashSet<>();
                }
                itemSet.add(lmSelfGoods);
                downMap.put(lmSelfGoods.getUserUuid(), itemSet);
            });

            //遍历map数据
            downMap.forEach((userUuid, goodsSet) -> {

                MyLambdaQueryWrapper<KsStoreUser> userWrapper = new MyLambdaQueryWrapper<>();

                userWrapper.eq(KsStoreUser::getDelFlag, "0");

                userWrapper.eq(KsStoreUser::getUuid, userUuid);

                KsStoreUser user = ksStoreUserService.getOne(userWrapper);

                MyLambdaQueryWrapper<KsOauth> oauthWrapper = new MyLambdaQueryWrapper<>();

                oauthWrapper.eq(KsOauth::getDelFlag, "0");

                oauthWrapper.eq(KsOauth::getUserUuid, user.getUuid());

                KsOauth ksOauth = ksOauthService.getOne(oauthWrapper);


                //发起下架动作
                goodsSet.forEach(lmSelfGoods -> {

                    KsMerchantItemStatusUpdateRequest goods = new KsMerchantItemStatusUpdateRequest();
                    goods.setAccessToken(ksOauth.getAccessToken());
                    goods.setRelItemId(lmSelfGoods.getRelItemId());
                    goods.setKwaiItemId(Long.valueOf(lmSelfGoods.getKwaiItemId()));

                    AccessTokenKsMerchantClient tokenKsMerchantClient
                            = new AccessTokenKsMerchantClient("", KsConfigInfo.appKey, KsConfigInfo.signSecret);

                    KsMerchantItemStatusUpdateResponse response = null;
                    try {
                        response = tokenKsMerchantClient.execute(goods);

                        if (response.getResult() == 1) {

                            lmSelfGoods.setKsSellStatus(2);
                            lmSelfGoodsService.updateById(lmSelfGoods);
                        }

                    } catch (KsMerchantApiException e) {
                        e.printStackTrace();
                    }
                });

            });

        }
    }


    @Scheduled(fixedDelay = 10 * 1000)//一小时更新一次
    public void updateLmGoodsDetails() {

        MyLambdaQueryWrapper<LmGoods> LmWrapper = new MyLambdaQueryWrapper<LmGoods>().eq(LmGoods::getDelFlag, "0");

        LmWrapper.isNull(LmGoods::getPicList);

        List<LmGoods> lmGoodsList = lmGoodsService.list(LmWrapper);

        List<LmGoodsDetails> lmGoodsDetailsList = lmGoodsList.stream().map(lmGoods -> {
            QueryItemDetailRequest request = new QueryItemDetailRequest();
            request.setBizId(LmConfig.LZ_BIZ_ID);
            request.setItemId(lmGoods.getItemId());

            try {
                QueryItemDetailResponse response = client.getAcsResponse(request);
                QueryItemDetailResponse.Item item = response.getItem();


                MyLambdaQueryWrapper<LmGoodsDetails> queryWrapper = new MyLambdaQueryWrapper<>();

                queryWrapper.eq(LmGoodsDetails::getItemId, item.getItemId());
                queryWrapper.eq(BaseEntity::getDelFlag, "0");

                LmGoodsDetails lmGoodsDetails = lmGoodsDetailsService.getOne(queryWrapper);

                if (lmGoodsDetails == null) {
                    lmGoodsDetails = new LmGoodsDetails();
                }
                CopyUtils.copyProperties(item, lmGoodsDetails);

                lmGoodsDetails.setMainPicPrl(item.getMainPicUrl());
                lmGoodsDetails.setSkus(JSON.toJSONString(item.getSkus()));
                lmGoodsDetails.setExtJson(item.getExtJson());
                lmGoodsDetails.setLmItemId(item.getLmItemId());

                String picList = item.getDescOption();

                if (StringUtils.isNotEmpty(picList)) {
                    try {
                        List<String> srcList = new ArrayList<>(); //用来存储获取到的图片地址
                        Pattern p = Pattern.compile("<(img|IMG)(.*?)(>|></img>|/>)");//匹配字符串中的img标签
                        Matcher matcher = p.matcher(picList);
                        boolean hasPic = matcher.find();
                        if (hasPic)//判断是否含有图片
                        {
                            while (hasPic) //如果含有图片，那么持续进行查找，直到匹配不到
                            {
                                String group = matcher.group(2);//获取第二个分组的内容，也就是 (.*?)匹配到的
                                Pattern srcText = Pattern.compile("(src|SRC)=(\"|\')(.*?)(\"|\')");//匹配图片的地址
                                Matcher matcher2 = srcText.matcher(group);
                                if (matcher2.find()) {
                                    srcList.add(matcher2.group(3));//把获取到的图片地址添加到列表中
                                }
                                hasPic = matcher.find();//判断是否还有img标签
                            }
                            lmGoods.setPicList(JSON.toJSONString(srcList));
                            lmGoodsService.updateById(lmGoods);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                return lmGoodsDetails;

            } catch (ClientException e) {
                e.printStackTrace();
            }
            return null;
        }).filter(Objects::nonNull).collect(Collectors.toList());
        if (lmGoodsDetailsList.size() > 0) {
            lmGoodsDetailsService.saveOrUpdateBatch(lmGoodsDetailsList);
        }
    }

//    @Scheduled(fixedDelay = 160 * 1000)
//    @PostConstruct

    /**
     * 暂时不用
     */
    public void updateLmGoodsInventory() {

        List<LmGoodsDetails> lmGoodsList = lmGoodsDetailsService.list(new MyLambdaQueryWrapper<LmGoodsDetails>().eq(LmGoodsDetails::getDelFlag, "0"));

        lmGoodsList.stream().forEach(lmGoods -> {
            QueryItemInventoryRequest request = new QueryItemInventoryRequest();
            request.setBizId(LmConfig.LZ_BIZ_ID);


            List<QueryItemInventoryRequest.ItemList> itemListList = new ArrayList<>();

            QueryItemInventoryRequest.ItemList itemList = new QueryItemInventoryRequest.ItemList();

            itemListList.add(itemList);

            itemList.setItemId(lmGoods.getItemId());

            List<QueryItemDetailResponse.Item.Sku> skuList = JSONArray.parseArray(lmGoods.getSkus(), QueryItemDetailResponse.Item.Sku.class);

            List<Long> skuIdSet = skuList.stream().map(QueryItemDetailResponse.Item.Sku::getSkuId).collect(Collectors.toList());
            itemList.setSkuIdLists(skuIdSet);
            request.setItemLists(itemListList);

            try {
                QueryItemInventoryResponse response = client.getAcsResponse(request);
                System.out.println(JSON.toJSONString(response.getItemList()));

            } catch (ClientException e) {
                e.printStackTrace();
            }

        });

    }


    public static void main(String[] args) {


        String content = "<p><img src=\"https://img.alicdn.com/imgextra/i3/2208554397276/O1CN01GO9poL23cSQK3iatD_!!2208554397276-0-scmitem18000.jpg\" align=\"absmiddle\"><img src=\"https://img.alicdn.com/imgextra/i2/2208554397276/O1CN01McIvTn23cSQNKj6OH_!!2208554397276-0-scmitem18000.jpg\" align=\"absmiddle\"><img src=\"https://img.alicdn.com/imgextra/i2/2208554397276/O1CN01jv3sOO23cSQLOu4Ey_!!2208554397276-0-scmitem18000.jpg\" align=\"absmiddle\"><img src=\"https://img.alicdn.com/imgextra/i4/2208554397276/O1CN01qLCICZ23cSQKRVXZ1_!!2208554397276-0-scmitem18000.jpg\" align=\"absmiddle\"><img src=\"https://img.alicdn.com/imgextra/i1/2208554397276/O1CN01f4t17X23cSQEcMmbm_!!2208554397276-0-scmitem18000.jpg\" align=\"absmiddle\"><img src=\"https://img.alicdn.com/imgextra/i3/2208554397276/O1CN01CoPCEK23cSQK3gVzb_!!2208554397276-0-scmitem18000.jpg\" align=\"absmiddle\"><img src=\"https://img.alicdn.com/imgextra/i4/2208554397276/O1CN01gc3fyU23cSQNKhpNr_!!2208554397276-0-scmitem18000.jpg\" align=\"absmiddle\"><img src=\"https://img.alicdn.com/imgextra/i4/2208554397276/O1CN01DdKy3y23cSQHNA6fi_!!2208554397276-0-scmitem18000.jpg\" align=\"absmiddle\"><img src=\"https://img.alicdn.com/imgextra/i1/2208554397276/O1CN019anw7b23cSQM2aPa7_!!2208554397276-0-scmitem18000.jpg\" align=\"absmiddle\"><img src=\"https://img.alicdn.com/imgextra/i4/2208554397276/O1CN01fDfeGo23cSQM2XjFr_!!2208554397276-0-scmitem18000.jpg\" align=\"absmiddle\"><img src=\"https://img.alicdn.com/imgextra/i3/2208554397276/O1CN01y0cNsA23cSQH8BhGx_!!2208554397276-0-scmitem18000.jpg\" align=\"absmiddle\"> </p>";


        //String content ="<html>...<div><img alt ='xxx' src='yyy'><img alt='xxx' src='mmm'></div></html>"
        List<String> srcList = new ArrayList<String>(); //用来存储获取到的图片地址
        Pattern p = Pattern.compile("<(img|IMG)(.*?)(>|></img>|/>)");//匹配字符串中的img标签
        Matcher matcher = p.matcher(content);
        boolean hasPic = matcher.find();
        if (hasPic == true)//判断是否含有图片
        {
            while (hasPic) //如果含有图片，那么持续进行查找，直到匹配不到
            {
                String group = matcher.group(2);//获取第二个分组的内容，也就是 (.*?)匹配到的
                Pattern srcText = Pattern.compile("(src|SRC)=(\"|\')(.*?)(\"|\')");//匹配图片的地址
                Matcher matcher2 = srcText.matcher(group);
                if (matcher2.find()) {
                    srcList.add(matcher2.group(3));//把获取到的图片地址添加到列表中
                }
                hasPic = matcher.find();//判断是否还有img标签
            }

        }
        System.out.println("匹配到的内容：" + srcList);
    }

}
